package book.chapter05.$5_3_1;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;

//Chapter: 5.3.1 Java API -> 创建连接 -> 创建一个最基本的ZooKeeper对象实例
public class ZooKeeper_Constructor_Usage_Simple implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    /**
     * 说明：zk 客户端与服务端会话建立是一个异步的过程：处理完客户端初始化后立即返回；此时在会话的声明周期状态为：CONNECTING;
     * 之后真正创建会话后，服务端会向会话对于的客户端发送一个事件通知；客户端只有收到这个通知，才算真正建立会话！
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        String connStr = "domain1.book.zookeeper:2181";
        connStr = "192.168.56.10:2181";
        ZooKeeper zookeeper = new ZooKeeper(connStr,
                5000, //
                new ZooKeeper_Constructor_Usage_Simple());
        System.out.println(zookeeper.getState());
        try {
            connectedSemaphore.await();
        } catch (InterruptedException e) {
        }
        System.out.println("ZooKeeper session established.");
    }

    /**
     * 负责处理来自 server 的 watch 通知：收到服务端发来的 SyncConnected 事件后，解除主程序在 CountDownLatch 上的阻塞。
     * 至此，才算会话重建完毕！
     *
     * @param event
     */
    public void process(WatchedEvent event) {
        System.out.println("Receive watched event：" + event);
        if (KeeperState.SyncConnected == event.getState()) {
            connectedSemaphore.countDown();
        }
    }
}